package com.yachang.qym.usbhost.service;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.util.Log;

import com.github.nkzawa.socketio.client.IO;
import com.yachang.qym.usbhost.utils.AllData;

import org.json.JSONObject;

import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;

import static com.yachang.qym.usbhost.utils.API.mSocket;
import static com.yachang.qym.usbhost.utils.API.serverUrl;

/**
 * Created by qinyuanmao on 2017/3/15.
 */

public class ScreenOnService extends Service {
    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();

		/* 注册广播 */
        IntentFilter mScreenOnFilter = new IntentFilter("android.intent.action.SCREEN_ON");
        ScreenOnService.this.registerReceiver(mScreenOnReceiver, mScreenOnFilter);
    }

    public void onDestroy() {
        super.onDestroy();
        this.unregisterReceiver(mScreenOnReceiver);
        // 在此重新启动,使服务常驻内存
        startService(new Intent(this, ScreenOnService.class));
    }

    private BroadcastReceiver mScreenOnReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals("android.intent.action.SCREEN_ON")) {
                try {
                    mSocket = IO.socket(serverUrl);
                    mSocket.connect();
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("fid", AllData.userModel.getFirecompany_id());
                    map.put("oid", AllData.outPolice_id);
                    JSONObject jsonObject = new JSONObject(map);
                    mSocket.emit("reConnect", jsonObject);
                } catch (URISyntaxException e) {
                    e.printStackTrace();
                }
            }
        }
    };
}
